#!/bin/bash

source repo_info.cfg

# GitLab Addr
GITLAB_URL="https://git.realthon.com"

# GitLab API endpoint
GITLAB_API=${GITLAB_URL}"/api/v4/projects"

# GitLab personal access token
GITLAB_TOKEN="glpat-wxyZPwNvPTvfrdfxxA4d"

# GitLab group or user name
GITLAB_GROUP_ID="964"
GITLAB_GROUP_NAME="mcu_dev/gd_dev/gd32g5xx"

# URL-encoded path of the group(%2F for /)
GITLAB_GROUP_NAME_URL="mcu_dev%2Fgd_dev%2Fgd32g5xx"

# GitLab branch name
NEWREPO_BRANCH="develop"
PROTECT_BRANCH="main"

# GitLab branch access level
# 0（或 None）：无访问，即没有推送和合并权限。
# 30（或 Developer）：开发者访问，允许推送和合并。
# 40（或 Maintainer）：维护者访问，允许推送和合并，并管理分支保护设置。
# 60（或 Admin）：管理员访问，拥有最高的推送、合并和设置权限。
MERGE_LEVEL=40
ACCESS_LEVEL=30

MAX_USER_NUMBER=${#GD_OWNER_NAME[@]}

# 传入参数 0，删除以上所有仓库，慎用！！！
if [ -n "$1" ]
then
	# echo "The \$1 is $1"
	if [ $1 -eq 0 ]
	then
		# Loop through the repository names and delete each repository
		for REPO_NAME in "${REPO_NAMES[@]}"
		do
			echo -e "\nDelete repo ${REPO_NAME}\n"
			# URL-encoded path of the project('/' is represented by "%2F")
			REPO_ID_URL=${GITLAB_GROUP_NAME_URL}%2F${REPO_NAME}
			curl -X DELETE ${GITLAB_API}/${REPO_ID_URL}?private_token=${GITLAB_TOKEN}
		done
		exit
	fi
fi


# 两个数组同时遍历，必须保证元素个数相同
# Get size of array
count=${#REPO_NAMES[@]}
for i in `seq 1 $count`
do
	echo "--- Roll $i"
	echo "new repo  : ${REPO_NAMES[i-1]}"
	echo "repo owner: ${REPO_OWNER[i-1]}"

	# Repository name & URL
	REPO_NAME=${REPO_NAMES[i-1]}
	# URL-encoded path of the project('/' is represented by "%2F")
	REPO_ID_URL=${GITLAB_GROUP_NAME_URL}%2F${REPO_NAME}


	# 1. 创建仓库，并保护分支
	# Create the repository, default_branch is "main" (Protected branches)
	info="name=${REPO_NAME}&path=${path}&namespace_id=${GITLAB_GROUP_ID}&initialize_with_readme=true&default_branch=main&private_token=${GITLAB_TOKEN}"
	curl -d $info ${GITLAB_API}

	# Create new branch of "develop"
	API_URL=${REPO_ID_URL}/"repository/branches"
	info="branch=${NEWREPO_BRANCH}&ref=main&private_token=${GITLAB_TOKEN}"
	curl -d $info ${GITLAB_API}/${API_URL}

	# Protect repository branches
	API_URL=${REPO_ID_URL}/"protected_branches"
	info="name=${PROTECT_BRANCH}&push_access_level=${ACCESS_LEVEL}&merge_access_level=${MERGE_LEVEL}&private_token=${GITLAB_TOKEN}"
	curl -d $info ${GITLAB_API}/${API_URL}


	# 2. 抓取 Owner，并添加到仓库
	# List of developer
	owner_list=${REPO_OWNER[i-1]}
	array=(${owner_list//// })
	for usr in ${array[@]}
	do
		for j in `seq 1 $MAX_USER_NUMBER`
		do
			if [[ ${GD_OWNER_NAME[j-1]} =~ $usr ]]
			then
				echo -e "\nUSER: ${GD_OWNER_NAME[j-1]}  ${GD_OWNER_SYMBOL[j-1]}\n"

				owner=${GD_OWNER_SYMBOL[j-1]}
				# Add a member to a project
				API_URL=${REPO_ID_URL}/"members"
				info="username=${owner}&access_level=${ACCESS_LEVEL}&private_token=${GITLAB_TOKEN}"
				curl -d $info ${GITLAB_API}/${API_URL}

				# Print the repository URL
				echo -e "\nRepository created: ${GITLAB_URL}/${GITLAB_GROUP_NAME}/${REPO_NAME}.git\n"
				break
			fi
		done
	done
done
